package com.ssyshop.info.fragment;


import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.ssyshop.info.R;
import com.ssyshop.info.https.OkHttpClientManager;
import com.ssyshop.info.model.Attrs;
import com.ssyshop.info.model.Goods;
import com.ssyshop.info.receiver.Logger;
import com.ssyshop.info.utils.BitmapCache;
import com.ssyshop.info.utils.Config;
import com.ssyshop.info.utils.Tools;

import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 * 商品详情页
 */
public class GoodsInfoFragment extends Fragment implements View.OnClickListener{


    ViewPager viewPager;
    //图片数组
    private List<String> list_url = new ArrayList<String>();
    private ArrayList<View> viewlist;

    private NetworkImageView imageView;//是Volley提供的一个自定义View，可直接设置网络图片
    private RequestQueue queue;//利用ImageRequest对象简单、方便地进行网络图片的获取
    private ImageLoader imageLoader;//用于获取或缓存图片
    //点点
    private ViewGroup pointgroup;
    private ImageView[] pointarr;
    private int count = 0;
    private boolean flag = true;
    public Timer mTimer = new Timer();
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x001) {
                viewPager.setCurrentItem(count);
            }
        }

    };
    public GoodsInfoFragment() {
        // Required empty public constructor
    }


    private Goods goods;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getArguments().containsKey("goods")) {
            goods = (Goods) getArguments().getSerializable("goods");
        }
        View view = inflater.inflate(R.layout.fragment_goods_info, container, false);
        initView(view);
        initData();
        initEvent();
        return view;
    }

    private ImageView btn_share;
    private NetworkImageView shop_thumb;
    private TextView goods_name,goods_price,goods_num,btn_by,attr_values,shop_name,shop_goods_number,show_shop;
    private RelativeLayout btn_menu_0,btn_menu_1,btn_menu_2,goods_shop;
    private CheckBox check_attention;
    private WebView desc_webview;
    private List<Attrs> list_attrs;
    private void initView(View view) {
        queue = Volley.newRequestQueue(getActivity());
        imageLoader = new ImageLoader(queue, new BitmapCache());
        btn_share=view.findViewById(R.id.btn_share);
        goods_name=view.findViewById(R.id.goods_name);
        goods_price=view.findViewById(R.id.goods_price);
        goods_num=view.findViewById(R.id.goods_num);//销量
        btn_by=view.findViewById(R.id.btn_by);//包邮
        btn_menu_0=view.findViewById(R.id.btn_menu_0);//三包说明
        btn_menu_1=view.findViewById(R.id.btn_menu_1);//商品属性
        attr_values=view.findViewById(R.id.attr_values);//商品属性的值
        btn_menu_2=view.findViewById(R.id.btn_menu_2);//商品参数
        goods_shop=view.findViewById(R.id.goods_shop);//商品所在店铺是否关注的布局  默认不显示，该商品有店铺时显示
        shop_thumb=view.findViewById(R.id.shop_thumb);//店铺缩略图
        shop_name=view.findViewById(R.id.shop_name);//店铺名称
        shop_goods_number=view.findViewById(R.id.shop_goods_number);//店铺的商品种类数量
        show_shop=view.findViewById(R.id.show_shop);//"进店逛逛"按钮
        check_attention=view.findViewById(R.id.check_attention);//是否关注店铺按钮
        desc_webview=view.findViewById(R.id.desc_webview);//商品详情列表，显示商品详情图片
        viewPager=view.findViewById(R.id.viewpager_img);
        pointgroup=view.findViewById(R.id.pointgroup);
    }

    private void initData() {
        goods_name.setText(goods.getGoods_name());
        goods_price.setText(goods.getShop_price());
        goods_num.setText("销量："+goods.getSales_volume());
        for (int i=0;i<goods.getPictures().size();i++){
            list_url.add(goods.getPictures().get(i).getImg_url());
        }
        initHDP();
        list_attrs=goods.getAttrses();
        if (list_attrs!=null&&list_attrs.size()>0){
            String name="";
            for (int i=0;i<list_attrs.size();i++){
                name=name+list_attrs.get(i).getName()+" ";
            }
            attr_values.setText(name);
        }else {
            btn_menu_1.setVisibility(View.GONE);
        }

        WebSettings webSettings = desc_webview.getSettings();
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//把html中的内容放大webview等宽的一列中
        webSettings.setJavaScriptEnabled(true);//支持js
        webSettings.setBuiltInZoomControls(true); // 显示放大缩小
        webSettings.setSupportZoom(true); // 可以缩放
        webSettings.setLoadsImagesAutomatically(true); // 支持自动加载图片
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);// 支持内容重新布局

        desc_webview.setWebViewClient(new WebViewClient());
        desc_webview.setWebChromeClient(new WebChromeClient());
        desc_webview.loadDataWithBaseURL(null, getNewContent(goods.getGoods_desc()), "text/html", "utf-8", null);
        Log.i("goods_desc",goods.getGoods_desc());

    }
    private void initEvent() {
        btn_share.setOnClickListener(this);//分享按钮
        btn_menu_0.setOnClickListener(this);
        btn_menu_1.setOnClickListener(this);
        btn_menu_2.setOnClickListener(this);
        show_shop.setOnClickListener(this);//进店逛逛按钮
        //是否关注店铺按钮
        check_attention.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {


            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_share://分享

                break;
            case R.id.btn_menu_0://三包说明
                showBomtomDialog0();
                break;
            case R.id.btn_menu_1://商品属性

                break;
            case R.id.btn_menu_2://商品参数

                break;
            case R.id.show_shop://"进店逛逛"按钮

                break;
        }
    }



    //商城服务内容底部弹出
    private void showBomtomDialog0() {//底部弹出框
        final Dialog bottomDialog = new Dialog(getActivity(), R.style.BottomDialog);
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.item_bottom_0, null);
        contentView.findViewById(R.id.btn_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        layoutParams.height = getResources().getDisplayMetrics().heightPixels * 2 / 3;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }






    /**
     * 初始化幻灯片
     */
    private void initHDP() {
        viewlist = new ArrayList<View>();
        //设置图片组
        if (list_url != null && list_url.size() > 0) {
            for (int i = 0; i < list_url.size(); i++) {
                imageView = new NetworkImageView(getActivity());
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                //设置图片
                imageView.setImageUrl(Config.URL_SERVER  + list_url.get(i), imageLoader);
                imageView.setDefaultImageResId(R.mipmap.pic_zwt_0);
                imageView.setErrorImageResId(R.mipmap.pic_zwt_0);
                //设置图片id
                imageView.setId(i);
                viewlist.add(imageView);
            }
        } else {
            ImageView image = new ImageView(getActivity());
            image.setScaleType(ImageView.ScaleType.FIT_XY);
            image.setImageResource(R.mipmap.pic_zwt_0);
            //设置图片id
            image.setId(0);
            viewlist.add(image);
        }
        /*
         * viewpager加载适配器
         * MyPageAdapter为自定义适配器
         *
         */
        //传递上下文
        MyPageAdapter pageadapter2 = new MyPageAdapter(viewlist, getActivity());
        viewPager.setAdapter(pageadapter2);
        if (list_url != null && list_url.size() > 0) {
            //点数组
            pointarr = new ImageView[list_url.size()];
            //把点加入布局，和设置点状态
            for (int i = 0; i < list_url.size(); i++) {
                ImageView point = new ImageView(getActivity());

                //设置点大小
                point.setLayoutParams(new ViewGroup.LayoutParams(25, 25));
                pointarr[i] = point;
                //状态处理
                if (i == 0) {
                    pointarr[i].setBackgroundResource(R.mipmap.icon_point_pre);
                } else {
                    pointarr[i].setBackgroundResource(R.mipmap.icon_point);
                }
                //加入到容器
                pointgroup.addView(pointarr[i]);
            }
        } else {
            pointgroup.setVisibility(View.GONE);
        }
        //viewpager设置监听器
        viewPager.setOnPageChangeListener(listener);

        if (flag && list_url != null && list_url.size() > 1) {
            timerTask(); // 定时执行
            flag = false;
        }
    }

    //定时器
    public void timerTask() {
        //创建定时线程执行更新任务
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                count++;
                if (count >= pointarr.length) {
                    count = 0;
                }
                handler.sendEmptyMessage(0x001);
            }
        }, 3000, 3000);// 定时任务
    }

    /**
     * 监听幻灯片
     */
    ViewPager.OnPageChangeListener listener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        //比如切换到第二张图片，相应索引的点为选择状态，其他为未选中状态
        @Override
        public void onPageSelected(int position) {
            count = position;
            for (int i = 0; i < pointarr.length; i++) {
                pointarr[position].setBackgroundResource(R.mipmap.icon_point_pre);
                if (position != i) {
                    pointarr[i].setBackgroundResource(R.mipmap.icon_point);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };


    /**
     * 幻灯片适配器
     */
    public class MyPageAdapter extends PagerAdapter {
        private List<View> viewlist;
        private Context context;

        public MyPageAdapter(List<View> viewlist, Context context) {
            this.viewlist = viewlist;
            this.context = context;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return viewlist.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }


        //以下也是必要方法，不过要自己添加
        //实例化
        @Override
        public Object instantiateItem(View container, final int position) {
            // TODO Auto-generated method stub
            ((ViewPager) container).addView(viewlist.get(position));
            View view = viewlist.get(position);
            view.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    int i = v.getId();
                    String t = "你点击了图片的图片id为：" + i + "  图片position为：" + position;
//                    Toast.makeText(context, t, Toast.LENGTH_LONG).show();


                }

            });
            return viewlist.get(position);
        }


        //销毁
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            container.removeView(viewlist.get(position));
        }

    }

    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     **/
    public static String getNewContent(String htmltext) {
        try {
            Document doc = Jsoup.parse(htmltext);
            Elements elements = doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width", "100%").attr("height", "auto");
            }
            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }


}
